#include <errno.h>
#include <string.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <memory.h>
#include <sys/mman.h>
#include "mem.h"

void Xil_In32(unsigned long phyaddr, uint32_t val)
{
	int fd;
	volatile void *map_base;
	unsigned long base = phyaddr & PAGE_MASK;
	unsigned long pgoffset = phyaddr & (~PAGE_MASK);
	if((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1)
	{
		printf("open /dev/mem:\n");
		return;
	}
 
	map_base = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED,
			fd, base);
	if(map_base == MAP_FAILED)
	{
		printf("mmap:\n");
		close(fd);
		return;
	}
	// qlog_i("base :%#x,pgoffset:%#x, val:%#x", base, pgoffset, val);
	*(volatile uint32_t*)((uint8_t *) map_base + pgoffset) = val; 
	munmap((void *)map_base, PAGE_SIZE);
	usleep(1000);
	close(fd);
}
 
int Xil_Out32(uint64_t phyaddr)
{
	int fd;
	uint32_t val;
	volatile void *map_base;
	uint64_t base = phyaddr & PAGE_MASK;
	uint64_t pgoffset = phyaddr & (~PAGE_MASK);
	//open /dev/mem
	if((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1)
	{
		printf("open /dev/mem:\n");
		return -1;
	}
	val = getpagesize();
	//mmap
	map_base = mmap(NULL, 0x400, PROT_READ | PROT_WRITE, MAP_SHARED,
			fd, base);
	if(map_base == MAP_FAILED)
	{
		printf("mmap:\n");
		close(fd);
		return -1;
	}
	val = *(volatile uint32_t *)((unsigned long *) map_base + pgoffset);
	munmap((void *)map_base, PAGE_SIZE);
 	close(fd);
	usleep(100);
	return val;
}